package com.mzy.linear_struct;

import com.sun.org.apache.regexp.internal.REUtil;

import java.util.Arrays;

/**
 * @Author: codermzy
 * @Date: 2024/03/30/10:51
 * @Description:
 */
public class MyLinkedList<T> {

    private Node<T> head;
    private int size;

    public MyLinkedList() {
        this.size = 0;
        this.head = null;
    }

    public void add(T value) {
        if (head == null) {
            head = new Node<>(value);
        } else {
            Node<T> cur = head;
            while (cur.next != null) {
                cur = cur.next;
            }
            cur.next = new Node<>(value);
        }
        size++;

    }

    public void insert(T value, int pos) {
        if (head == null) {
            head = new Node<>(value);
        }
        Node<T> inserNode = new Node<>(value);
        if (pos == 0) {
            inserNode.next = head;
            head = inserNode;
        } else {
            Node<T> cur = head;
            Node<T> previous = head;
            int index = 0;

            while (index++ < pos) {
                previous = cur;
                cur = cur.next;
            }
            previous.next = inserNode;
            inserNode.next = cur;
        }
        size++;
    }


    public T remove(int pos) {
        if (pos < 0 || pos >= size) {
            throw new RuntimeException("非法位置!");
        }
        Node<T> removeNode = null;
        if (pos == 0) {
            removeNode = head;
            head = head.next;
        } else {
            int index = 0;
            Node<T> cur = head;
            Node<T> previous = head;
            while (index++ < pos) {
                previous = cur;
                cur = cur.next;
            }
            previous.next = cur.next;
            removeNode = cur;
        }
        size--;
        return removeNode.value;

    }

    public T[] traverse() {
        Node<T> cur = head;
        Object[] result = new Object[size];
        for (int i = 0; cur != null; i++, cur = cur.next) {
            result[i] = cur.value;
        }

        return (T[]) result;
    }

    public static void main(String[] args) {
        MyLinkedList<Integer> list = new MyLinkedList<>();
        list.add(1);
        list.add(2);
        list.add(3);

        System.out.println(Arrays.toString(list.traverse()));

        list.insert(10, 1);
        System.out.println(Arrays.toString(list.traverse()));
        System.out.println(list.remove(0));
        System.out.println(Arrays.toString(list.traverse()));
    }

}

class Node<T> {
    T value;
    Node<T> next;

    public Node(T value) {
        this.value = value;
    }
}